<template>
  <div class="text-sample-container">
    <div class="header">
      <div class="title">
        <el-icon>
          <Document />
        </el-icon>
        <span>Sample YAML</span>
      </div>
      <div class="actions">
        <el-button type="success" size="small" @click="importSample" :loading="importing">
          <el-icon>
            <Upload />
          </el-icon>
          导入
        </el-button>
        <el-button type="primary" size="small" @click="applySampleToFields" :disabled="!sampleText.trim()"
          :loading="applying">
          <el-icon>
            <Upload />
          </el-icon>
          应用
        </el-button>
      </div>
    </div>

    <div class="editor-container">
      <div ref="editorRef" class="editor"></div>
    </div>

    <!-- 隐藏的文件输入 -->
    <input ref="fileInputRef" type="file" accept=".yaml,.yml" style="display: none" @change="handleFileUpload" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { Document, Upload } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { invoke } from '@tauri-apps/api/core'
let monaco: any = null
let configureMonacoYaml: typeof import('monaco-yaml').configureMonacoYaml | null = null

const emit = defineEmits<{
  sampleChange: [text: string]
  applyToFields: [treeData: any[]]
}>()

const props = defineProps<{
  crdText?: string
}>()

const editorRef = ref<HTMLElement>()
const fileInputRef = ref<HTMLInputElement>()
const sampleText = ref('')
const applying = ref(false)
const importing = ref(false)
let editor: any = null

onMounted(async () => {
  await initEditor()
})

onBeforeUnmount(() => {
  if (editor) {
    editor.dispose()
  }
})

async function initEditor() {
  if (!editorRef.value) return
  if (!monaco) {
    monaco = (await import('monaco-editor'))
    configureMonacoYaml = (await import('monaco-yaml')).configureMonacoYaml
  }
  if (!monaco || !configureMonacoYaml) return
  // 配置YAML语言支持
  configureMonacoYaml(monaco)
  editor = monaco.editor.create(editorRef.value, {
    value: sampleText.value,
    language: 'yaml',
    theme: 'vs-dark',
    automaticLayout: true,
    tabSize: 2,
    insertSpaces: true,
    detectIndentation: false,
    minimap: { enabled: false },
    scrollBeyondLastLine: false,
    fontSize: 14,
    wordWrap: 'on',
    folding: true,
    lineNumbers: 'on',
    renderWhitespace: 'boundary',
    bracketPairColorization: { enabled: true },
  })

  // 监听编辑器内容变化
  editor.onDidChangeModelContent(() => {
    if (editor) {
      const value = editor.getValue()
      sampleText.value = value
      emit('sampleChange', value)
    }
  })

  // 添加撤销/重做快捷键
  editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyZ, () => {
    editor?.trigger('source', 'undo', null)
  })

  editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KeyZ, () => {
    editor?.trigger('source', 'redo', null)
  })
}

function importSample() {
  fileInputRef.value?.click()
}

async function handleFileUpload(event: Event) {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]

  if (!file) return

  importing.value = true

  try {
    const text = await file.text()

    // 验证YAML格式
    try {
      await invoke('validate_yaml', { yamlText: text })
      sampleText.value = text
      if (editor) {
        editor.setValue(text)
      }
      
      // 自动执行应用到字段
      await autoApplyToFields()
      
    } catch (error) {
      ElMessage.error(`YAML格式错误: ${error}`)
    }
  } catch (error) {
    ElMessage.error('文件读取失败')
  } finally {
    importing.value = false
    // 清空文件输入
    target.value = ''
  }
}

// 自动应用到字段（导入时调用）
async function autoApplyToFields() {
  if (!sampleText.value.trim()) {
    return
  }

  if (!props.crdText?.trim()) {
    ElMessage.warning('请先加载CRD定义')
    return
  }

  try {
    // 调用Rust后端解析sample并生成descriptors
    const result = await invoke('apply_sample_to_fields', {
      crdText: props.crdText,
      sampleText: sampleText.value
    })

    emit('applyToFields', result as any[])
  } catch (error) {
    console.error('自动应用Sample失败:', error)
    ElMessage.error(`自动应用Sample失败: ${error}`)
  }
}

async function applySampleToFields() {
  if (!sampleText.value.trim()) {
    ElMessage.warning('请先输入Sample YAML内容')
    return
  }

  if (!props.crdText?.trim()) {
    ElMessage.warning('请先加载CRD定义')
    return
  }

  applying.value = true

  try {
    // 调用Rust后端解析sample并生成descriptors
    const result = await invoke('apply_sample_to_fields', {
      crdText: props.crdText,
      sampleText: sampleText.value
    })

    emit('applyToFields', result as any[])
  } catch (error) {
    console.error('应用Sample失败:', error)
    ElMessage.error(`应用Sample失败: ${error}`)
  } finally {
    applying.value = false
  }
}

// 监听CRD变化
watch(() => props.crdText, () => {
  // CRD变化时可以做一些处理
  console.log('CRD changed, current sample:', sampleText.value)
})

// 暴露方法给父组件
defineExpose({
  getSampleText: () => sampleText.value,
  setSampleText: (text: string) => {
    sampleText.value = text
    if (editor) {
      editor.setValue(text)
    }
  }
})
</script>

<style lang="scss" scoped>
.text-sample-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  border: 1px solid #e1e8ed;
  border-radius: 8px;
  background: #ffffff;
  overflow: hidden;

  .header {
    padding: 12px 16px;
    background: #f8f9fa;
    border-bottom: 1px solid #e1e8ed;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;

    .title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
      color: #2c3e50;

      .el-icon {
        color: #409eff;
      }
    }

    .actions {
      display: flex;
      gap: 8px;
    }
  }

  .editor-container {
    flex: 1;
    min-height: 0;
    position: relative;

    .editor {
      height: 100%;
      width: 100%;
    }
  }
}

// 深色主题下的样式调整
:deep(.monaco-editor) {
  .margin {
    background: #1e1e1e;
  }
}
</style>